package com.maigao.core.login.handler;

import com.maigao.core.config.WxConfig;
import com.maigao.core.login.annotation.ThirdLoginHandler;
import com.maigao.core.login.dto.WeixinLoginRecord;
import com.maigao.entity.DomainConstant;
import com.maigao.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author awei
 * @description: 微信小程序三方登录
 * @date 2022/5/19 10:20 下午
 */
@Component
@ThirdLoginHandler(value = DomainConstant.ThirdLogin.WX)
public class WxThirdLoginHandler extends BaseHandler implements IThirdLoginHandler<String, WeixinLoginRecord> {

    @Autowired
    private WxConfig wxConfig;

    @Override
    public WeixinLoginRecord search(String code) {
        WeixinLoginRecord record = new WeixinLoginRecord();
        StringBuffer url = new StringBuffer(wxConfig.getWxAuthUrl());
        url.append("?grant_type=authorization_code").append("&appid=").append(wxConfig.getAppId()).append("&secret=")
                .append(wxConfig.getSecretId()).append("&js_code=").append(code);

        String resp = HttpUtils.doGet(url.toString());
        Map<String, String> tokenMap = processResult(WeixinLoginRecord.tokenList, resp);

        if (null != tokenMap) {
            record.setAccess_token(tokenMap.get(WeixinLoginRecord.ACCESS_TOKEN));
            record.setExpires_in(tokenMap.get(WeixinLoginRecord.EXPIRES_IN));
            record.setOpenId(tokenMap.get(WeixinLoginRecord.OPENID));

            url.setLength(0);
            // todo 是否有获取用户相关信息的接口 待确认
           /* url.append(userInfoURL).append("?access_token=").append(record.getAccess_token()).append("&openid=")
                    .append(record.getOpenId());
            requestStr = doRequest(url.toString(), client);
            Map<String, String> urlInfoMap = processResult(WeixinLoginRecord.urlInfoList, requestStr);
            record.setHeadImgUrl(urlInfoMap.get(WeixinLoginRecord.HEADIMGURL));
            record.setNickName(urlInfoMap.get(WeixinLoginRecord.NICKNAME));
            record.setProvince(urlInfoMap.get(WeixinLoginRecord.PROVINCE));
            // record.setSex(Integer.parseInt(urlInfoMap.get(WeixinLoginRecord.SEX)));
            record.setUnionid(urlInfoMap.get(WeixinLoginRecord.UNIONID));*/

        }
        return record;
    }
}
